package com.cluck.pay.controller;

import com.cluck.pay.entity.PayInfo;
import com.cluck.pay.service.PayInfoService;
import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付信息控制层
 * @author cluck
 * @version 1.0
 * @date 2020/5/9 17:59
 */
@Controller
@RequestMapping("/pay")
@Slf4j
public class PayInfoController {

    @Autowired
    private PayInfoService payInfoService;
    @Autowired
    private WxPayConfig wxPayConfig;

    /**
     * 创建支付
     * @param orderId
     * @param amount
     * @param bestPayTypeEnum
     * @return
     */
    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("amount") BigDecimal amount,
                               @RequestParam("payType") BestPayTypeEnum bestPayTypeEnum
    ) {
        PayResponse response = payInfoService.create(orderId, amount, bestPayTypeEnum);

        //支付方式不同，渲染就不同, WXPAY_NATIVE使用codeUrl,  ALIPAY_PC使用body
        Map<String, String> map = new HashMap<>();
        if (bestPayTypeEnum == BestPayTypeEnum.WXPAY_NATIVE) {
            map.put("codeUrl", response.getCodeUrl());
            map.put("orderId", orderId);
            map.put("returnUrl", wxPayConfig.getReturnUrl());
            return new ModelAndView("createForWxNative", map);
        }else if (bestPayTypeEnum == BestPayTypeEnum.ALIPAY_PC) {
            map.put("body", response.getBody());
            return new ModelAndView("createForAlipayPc", map);
        }

        throw new RuntimeException("暂不支持的支付类型");
    }


    /**
     * 支付成功回调
     * @param notifyData
     * @return
     */
    @PostMapping("/notify")
    @ResponseBody
    public String asyncNotify(@RequestBody String notifyData) {
        return payInfoService.asyncNotify(notifyData);
    }

    /**
     * 根据订单号查询订单
     * @return
     */
    @GetMapping("/queryOrderId")
    @ResponseBody
    public PayInfo queryByOrderId(@RequestParam String orderId) {
        log.info("查询支付记录....");
        return payInfoService.queryByOrderId(orderId);
    }
}
